<template>
  <div class="avatar">
    <div class="title">
      <van-nav-bar title="修改头像">
        <template #left>
          <i
            class="iconfont iconbtn_nav_back iconStyle"
            @click="$router.push('/info')"
          ></i>
        </template>
        <template #right>
          <span v-if="saveAvatar" @click="saveChange">保存</span>
        </template>
      </van-nav-bar>
    </div>
    <div class="imgBox">
      <van-uploader
        v-model="fileList"
        :max-count="1"
        preview-size="200px"
        :before-read="beforeRead"
        :after-read="afterRead"
      >
      </van-uploader>
    </div>
  </div>
</template>
<script>
import { upload, getEdit, getuserInfo } from '@/api/login.js'
export default {
  data () {
    return {
      imgId: 0,
      saveAvatar: false,
      fileList: [
        {
          url: this.$store.state.userInfo.avatar
        }
      ]
    }
  },
  created () {
    this.avatar = this.$store.state.userInfo.avatar
  },
  methods: {
    beforeRead (file) {
      if (
        file.type !== 'image/jpeg' &&
        file.type !== 'image/png' &&
        file.type !== 'image/gif'
      ) {
        this.$toast.fail('请上传 jpg 格式图片')
        return false
      }
      return true
    },
    afterRead (file) {
      // 此时可以自行将文件上传至服务器
      file.status = 'uploading'
      file.message = '上传中...'
      // console.log(file)
      upload(file.file).then(res => {
        // 保存修改头像时需要的id
        this.imgId = res.data.data[0].id
        this.saveAvatar = true
        file.status = 'done'
        // console.log(res)
      })
    },
    // 保存头像
    saveChange () {
      this.$toast.loading({
        message: '加载中',
        duration: 0
      })
      getEdit({ avatar: this.imgId }).then(res => {
        // console.log(res)
        getuserInfo().then(res => {
          res.data.data.avatar = 'http://127.0.0.1:1337' + res.data.data.avatar
          this.$store.commit('setUserInfo', res.data.data)
        })
        this.$toast.success('修改成功')
        this.$router.push('/info')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.avatar {
  font-size: 12px;
  width: 100%;
  font-size: 12px;
  .title {
    .iconStyle {
      font-size: 44px;
    }
    /deep/.van-nav-bar__left {
      padding-left: 0;
    }
    /deep/.van-nav-bar__title {
      font-weight: 700;
    }
  }
  .content {
    padding: 15px;
  }
  .txtstyle {
    background-color: #f5f3f4;
  }
  .imgBox {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    width: 100%;
    .upstyle {
      margin: 0 auto;
      width: 200px;
      height: 200px;
    }
  }
}
</style>
